package cn.phantom.pooltest;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

@Slf4j(topic = "c.TestSubmit")
public class TestSubmit {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(1);

        // method1(pool);

        // method2(pool);

        String str = pool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(1000);
                    return "1";
                },
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(500);
                    return "2";
                },
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(2000);
                    return "3";
                }
        ));
        log.debug("{}", str);


    }

    private static void method1(ExecutorService pool) throws InterruptedException, ExecutionException {
        Future<String> submit = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.debug("running");
                TimeUnit.SECONDS.sleep(1);
                return "ok";
            }
        });

        log.debug("result: {}", submit.get());
    }

    private static void method2(ExecutorService pool) throws InterruptedException {
        List<Future<Object>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin");
                    Thread.sleep(1000);
                    return "1";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(500);
                    return "2";
                },
                () -> {
                    log.debug("begin");
                    Thread.sleep(2000);
                    return "3";
                }
        ));
        futures.forEach( f -> {
            try {
                log.debug("{}", f.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
